<template>
  <div class="ad-template-label">
    <x-form :ref="setItemRef" :loading="loading" :model="params" :rules="rules" label-position="top">
      <n-form-item :label="getProps.params.description" prop="default">
        <div>
          <dl v-for="(item, index) in list" :key="index">
            <dt>{{ item.label_category }}</dt>
            <dd>
              <div
                v-for="label in item.label"
                :key="label"
                :class="{ active: getProps.params.default.some((s) => s.content === label) }"
                class="item"
                @click="onChange(label)"
                >{{ label }}</div
              >
            </dd>
          </dl>
        </div>
      </n-form-item>
    </x-form>
  </div>
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router'
  import XForm from '@/components/x-form/index.vue'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { useStore } from '@/store'
  import { NFormItem, useMessage } from 'naive-ui'
  const route = useRoute()
  const store = useStore()
  const message = useMessage()
  const props = defineProps({
    params: {
      type: Object,
      default: () => ({})
    },
    type: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    }
  })
  const getProps = reactive(props)
  const emit = defineEmits(['change'])
  const isEdit = computed(() => {
    return !!store.state.intelligent.data.id
  })
  const base = computed(() => {
    return !!store.state.intelligent.data.base
  })
  const accountCode = computed(() => {
    return store.state.intelligent.data.accountCode
  })
  const dimension = computed(() => {
    return getProps.params.array_property
  })

  const loading = ref(true)
  const rules = ref({
    default: []
  })
  const list = ref([])
  const itemRefs = {}
  const setItemRef = (el: any) => {
    if (el) {
      const key = getProps.params.name
      itemRefs[key] = el
    }
  }
  onMounted(() => {
    const itemKey = getProps.params.name
    const itemRef = itemRefs[itemKey]
    if (!getProps.params.default) {
      getProps.params.default = []
    }
    initRules()
    getLabelList()
  })

  // 初始化校验规则
  function initRules() {
    // 自定义长度校验
    const validateLength = (rule, value, callback) => {
      if (getProps.params.required) {
        const msg = `最少选择${dimension.value.min_number}个${getProps.params.description}，最多只能选择${dimension.value.max_number}个${getProps.params.description}`
        if (
          getProps.params.default.length > dimension.value.max_number ||
          getProps.params.default.length < dimension.value.min_number
        ) {
          callback(msg)
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 最小、最大
    rules.value.default.push({
      validator: validateLength,
      trigger: ['blur', 'change']
    })
    // 必填、可选
    if (getProps.params.required) {
      rules.value.default.push({
        required: getProps.params.required,
        message: `${getProps.params.description}不能为空`,
        trigger: ['blur', 'change']
      })
    }
  }
  // 校验
  function validate() {
    return new Promise((resolve, reject) => {
      itemRefs[getProps.params.name].validate((errors) => {
        if (!errors) {
          resolve(getProps.params.default)
        } else {
          message.warning(`请选择${getProps.params.description}`)
          resolve(false)
        }
      })
    })
  }
  // 获取标签列表
  function getLabelList() {
    store
      .dispatch('intelligent/getAdsLabelList', {
        accountCode: accountCode.value
      })
      .then((res) => {
        list.value = res.data
        loading.value = false
      })
  }
  // 选择标签
  function onChange(item) {
    if (typeof getProps.params.default === 'object') {
      const index = getProps.params.default.findIndex((s) => s.content === item)
      if (index === -1) {
        if (getProps.params.default.length < dimension.value.max_number) {
          getProps.params.default.push({
            content: item
          })
        } else {
          message.warning(`最多只能选择${dimension.value.max_number}个${getProps.params.description}`)
        }
      } else {
        getProps.params.default.splice(index, 1)
      }
    } else {
      getProps.params.default = [
        {
          content: item
        }
      ]
    }
  }
  defineExpose({
    validate
  })
</script>

<style scoped lang="scss">
  @import '@/assets/styles/var';
  .ad-template-label {
    dl,
    dt,
    dd {
      padding: 0;
      margin: 0;
    }
    dl {
      padding-left: 1em;
    }
    dt {
      font-weight: bold;
    }
    dd {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }
    .item {
      padding: 5px 10px;
      line-height: 1;
      border: 1px solid #dcdcdc;
      margin: 0 6px 6px 0;
      cursor: pointer;
      &:hover {
        background-color: #fafafa;
      }
      &.active {
        background-color: $primaryColor;
        color: #fff;
        border-color: $primaryColor;
      }
    }
  }
</style>
